let lastSrcs; //上一次获取到的script地址
let needTip = true; // 默认开启提示
import { ElMessageBox } from "element-plus";
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm;
export async function extractNewScripts() {
	const html = await fetch("/?timestep=" + Date.now()).then(resp => resp.text());
	scriptReg.lastIndex = 0;
	let result = [];
	let match;
	while ((match = scriptReg.exec(html))) {
		result.push(match.groups.src);
	}
	return result;
}

export async function needUpdate() {
	const newScripts = await extractNewScripts();
	if (!lastSrcs) {
		lastSrcs = newScripts;
		return false;
	}
	let result = false;
	if (lastSrcs.length !== newScripts.length) {
		result = true;
	}
	for (let i = 0; i < lastSrcs.length; i++) {
		if (lastSrcs[i] !== newScripts[i]) {
			result = true;
			break;
		}
	}
	lastSrcs = newScripts;
	return result;
}
const DURATION = 20000;

export function autoRefresh() {
	setTimeout(async () => {
		const willUpdate = await needUpdate();
		if (willUpdate) {
			// const result = confirm("页面有更新，请刷新查看");
			// if (result) {
			//   location.reload();
			// }
			MessageBox.confirm("检测到新版本, 请点击确定刷新页面！", "提示", {
				confirmButtonText: "确定",
				showCancelButton: false,
				cancelButtonText: "取消",
				showClose: false,
				closeOnClickModal: false,
				type: "warning"
			})
				.then(() => {
					location.reload(); // 刷新当前页
				})
				.catch(() => {
					console.log("取消了");
				});
			needTip = false; // 关闭更新提示，防止重复提醒
		}
		if (needTip) {
			autoRefresh();
		}
	}, DURATION);
}
